package com.jyu.controller;

import com.baomidou.mybatisplus.core.metadata.IPage;
import com.jyu.domain.Position;
import com.jyu.utils.R;
import com.jyu.service.PositionService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.time.Duration;
import java.time.LocalDateTime;
import java.util.List;

@Slf4j
@RestController
@RequestMapping("/pages/position")
public class PosController {

    @Autowired
    private PositionService positionService;

    @Autowired
    private RabbitTemplate rabbitTemplate;

    @GetMapping
    public R getAll(){
//        log.info(String.valueOf(positionService.list()));
        return new R(true,positionService.list());
    }

    @PostMapping
    public R save(@RequestBody Position position){
        boolean result = positionService.savePosition(position);
        System.out.println(position.getId());
//        rabbitTemplate.convertAndSend("employ.position.insert",position.getId());
        positionService.addPositionDocument(position.getId());
        return new R(result);
    }

    @PutMapping
    public R update(@RequestBody Position position){
        boolean result = positionService.modify(position);
//        rabbitTemplate.convertAndSend("employ.position.insert",position.getId());
        positionService.addPositionDocument(position.getId());
        return new R(result);
    }

    @GetMapping("{id}")
    public R getById(@PathVariable Integer id) {
        return new R(true, positionService.getById(id));
    }

    @DeleteMapping("{id}")
    public R delete(@PathVariable Integer id){
        boolean result = positionService.delete(id);
//        rabbitTemplate.convertAndSend("employ.position.delete",id);
        positionService.deletePositionDocument(id);
        return new R(result);
    }

    @GetMapping("{currentPage}/{pageSize}")
    public R getPage(@PathVariable int currentPage, @PathVariable int pageSize, Position position) {

        IPage<Position> page = positionService.getPage(currentPage, pageSize, position);
        //如果当前页码值大于总页码值，那么重新执行查询操作，使用最大页码值作为当前页码值
        if (currentPage > page.getPages()) {
            page = positionService.getPage((int) page.getPages(), pageSize, position);//一次性删除过多可能有bug
        }
        return new R(true, page);
    }

    @GetMapping("/field")
    public R getField()
    {
        List<String> field = positionService.getField();
        return new R(true,field);
    }

    /**
     * 员工退出
     * @param request
     * @return
     */
    @PostMapping("/signOut")
    public R logout(HttpServletRequest request){
        //清理Session中保存的当前登录员工的id
        request.getSession().removeAttribute("manager");
        return new R(true);
    }
}
